package servlet;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.Student;
import service.StudentService;
import service.impl.StudentServiceImpl;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/student/*")
public class StudentServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	public void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  {
		StudentService studentService = new StudentServiceImpl();
		List<Student> students = studentService.findAll();
		request.getSession().setAttribute("students", students);
		response.sendRedirect("showStudent.jsp");
	}

	public void selectStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String stuname = request.getParameter("stuname");
		StudentService studentService = new StudentServiceImpl();
		List<Student> students = studentService.selectStudentByStuname(stuname);
		request.getSession().setAttribute("students", students);
		response.sendRedirect("../showStudent.jsp");
	}
	
	public void deleteStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String stuno = request.getParameter("stuno");
		StudentService studentService = new StudentServiceImpl();
		boolean flag = studentService.deleteStudent(stuno);
		if(flag) {
			List<Student> students = studentService.findAll();
			request.getSession().setAttribute("students", students);
			response.sendRedirect("../showStudent.jsp");
		}
	}
	
	public void updateStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String stuname = request.getParameter("stuname");
		System.out.println(stuname);
		StudentService studentService = new StudentServiceImpl();
		List<Student> students = studentService.selectStudentByStuname(stuname);
		request.getSession().setAttribute("students", students);
		response.sendRedirect("../update.jsp");
	}
	
	public void saveStudent(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String stuname = request.getParameter("stuname");
		String stuno = request.getParameter("stuno");
		String stusex = request.getParameter("stusex");
		Student stu = new Student(stuno, stuname, stusex);
		StudentService studentService = new StudentServiceImpl();
		boolean flag = studentService.SaveStudent(stu);
		if(flag) {
			List<Student> students = studentService.findAll();
			request.getSession().setAttribute("students", students);
			response.sendRedirect("../showStudent.jsp");
		}
	}
	
	
	

}
